#include "StdAfx.h"
#include "NewFileCommand.h"
#include "Utils.h"

NewFileCommand::NewFileCommand( const std::wstring &wDir, const std::wstring &tDir, const std::wstring &fName )
    : fileName( wDir ^ fName )
    , tempFileName(tDir ^ fName )
{}

Command* NewFileCommand::Clone() const {
    return new NewFileCommand( fileName, tempFileName );
}

NewFileCommand::~NewFileCommand()
{}

void NewFileCommand::Do()
{
    if ( FileUtils::FileExists( tempFileName ) ) {
        if (!::MoveFile( tempFileName.c_str(), fileName.c_str() ))
            throw CommandException();
    }
    else {
        HANDLE hFile = ::CreateFile(fileName.c_str(), GENERIC_WRITE, FILE_SHARE_READ, 0, CREATE_ALWAYS, 0, 0);
        if (hFile == INVALID_HANDLE_VALUE)
            throw CommandException();
        ::CloseHandle( hFile );
    }
}

void NewFileCommand::Undo()
{
    if ( FileUtils::FileSize( fileName ) > 0 ) {
        if (!::MoveFile( fileName.c_str(), tempFileName.c_str() ))
            throw CommandException();
    }
    else {
        if (!::DeleteFile( fileName.c_str() ))
            throw CommandException();
    }
}

